package com.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.persistence.Player;
import com.persistence.Reserve;
import com.persistence.TFootballTeam;
import com.persistence.TPlayer;
import com.service.PlayerService;
import com.service.TeamService;

@Controller
@SessionAttributes
public class TeamEditController2 extends AbstractController {
	ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
	TeamService teamDao = (TeamService) context.getBean("teamService");
	PlayerService playerDao = (PlayerService) context.getBean("playerService");
	
	@Override
	@RequestMapping(value = "/saveEditTeam2", method = RequestMethod.POST)
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		String teamId = req.getParameter("teamId");
		String teamName = req.getParameter("teamName");
		String idPlayer = req.getParameter("playerId");
		
		TFootballTeam team = new TFootballTeam();
		team.setIdTeam(Integer.parseInt(teamId));
		team.setTeamName(teamName);
		
		List<TPlayer> captain = team.getCaptains();

		TPlayer player = playerDao.findById(Integer.parseInt(idPlayer));
		
		captain.remove(player);
		team.setCaptains(captain);
		teamDao.update(team);
				
		List<TFootballTeam> list2 = teamDao.findAll();
		Map<String, Object> list3 = new HashMap<String, Object>();
		
		team = teamDao.findById(Integer.parseInt(teamId));
		List<TPlayer> playerList = playerDao.findByProperty("TFootballTeam", team, 0);
		
		Iterator i = playerList.iterator();
		List<Player> players = new ArrayList<Player>();
		List<Reserve> reserves = new ArrayList<Reserve>();
		
		while(i.hasNext()) {
			TPlayer tp = (TPlayer) i.next();
			if(tp instanceof Player){
				players.add((Player)tp);
			}else if(tp instanceof Reserve){
				reserves.add((Reserve)tp);
			}
		}
		
		list3.put("team", list2);
		list3.put("player", players);
		list3.put("reserve", reserves);
		list3.put("team2", team);
		req.setAttribute("list3", list3);
		res.sendRedirect("main.htm?module=team&action=view&teamid=" + teamId);
		return new ModelAndView("contact", "list3", list3);
	}

}
